// pages/delivery-address/delivery-address.js

var http = require("../../utils/http.js");
// var config = require("../../utils/config.js");

Page({
  data: {
    userid: "",
    defaultSize: 'mini',
    disabled: false,
    plain: true,
    loading: false,
    addressList: [],
    addAddress: '',
    order: -1
  },

  onLoad: function (option) {
    const util = require('../../utils/util')
    util.isLogin()
    if (option.order) {
      this.setData({
        order: option.order
      });
    }
    //设置个人信息
    this.setData({
      userid: wx.getStorageSync('userId')
    })
  },

  //新增收货地址
  onAddAddr: function (e) {
    wx.navigateTo({
      url: '/pages/editAddress/editAddress',
    })
  },

  //设置为默认地址
  onDefaultAddr: function (e) {
    var addrId = e.currentTarget.dataset.id;
    console.log("addrId", addrId)

    wx.showLoading();
    var params = {
      url: "/address/default",
      method: "PUT",
      data: {
        id: addrId,
      },
      callBack: function (res) {
        wx.hideLoading();
      }
    }
    http.request(params);
  },

  //加载地址列表
  onShow: function () {
    var ths = this;
    wx.showLoading();
    var params = {
      url: "/address",
      method: "GET",
      data: {
        userId: this.data.userid,
      },
      callBack: function (res) {
        console.log(res)
        ths.setData({
          addressList: res
        });
        wx.hideLoading();
      }
    }
    http.request(params);
  },

  // 修改地址 
  toEditAddress: function (e) {
    var addrId = e.currentTarget.dataset.addrid;
    wx.navigateTo({
      url: '/pages/editAddress/editAddress?addrId=' + addrId,
    })
  },
  //删除地址
  toDeleteAddress: function (e) {
    wx.showModal({
      title: '提示',
      content: '是否确认删除该地址',
      success: function (res) {
        if (res.confirm) {
          console.log('确定删除');
          var addrId = e.currentTarget.dataset.addrid;
          wx.showLoading();
          var params = {
            url: "/address",
            method: "DELETE",
            data: {
              addrId: addrId
            },
            callBack: function (res) {
              wx.hideLoading();
            }
          }
          http.request(params);
          wx.redirectTo({
            url: '/pages/delivery-address/delivery-address',
          })
        } else {
          console.log('取消删除');
        }
      }
    })
  },


  /**
   * 选择地址 跳转回提交订单页
   */
  selAddrToOrder: function (e) {
    console.log("item", e.currentTarget.dataset.item)
    if (this.data.order == 0) {
      var pages = getCurrentPages(); //当前页面
      var prevPage = pages[pages.length - 2]; //上一页面
      prevPage.setData({ //直接给上移页面赋值
        addrId: e.currentTarget.dataset.item.id,
        item: e.currentTarget.dataset.item,
        selAddress: 'yes'
      });
      wx.navigateBack({ //返回
        delta: 1
      })
    }
  }
})